import React from 'react';
import $ from 'jquery';
import Simditor from './es/Simditor';
import './styles/simditor.css';

export default class SimEditor extends React.Component {
  static propTypes = {
    name: React.PropTypes.string,
    input: React.PropTypes.string,
    output: React.PropTypes.func
  };

  static defaultProps = {
    input: '开始你的笔记!',
    onChange() {

    }
  };

  constructor(props) {
    super(props);
    this.state = {
      'content': props.input
    };
  }

  componentDidMount() {
    this.editor.setValue(this.state.content);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.input != this.state.content) {
      this.setState({content: nextProps.input}, ()=> {
        this.editor.setValue(this.state.content);
      });
    }
  }

  textareaRef(el) {
    if (this.editor) return;
    this.editor = this.editor || new Simditor({
        textarea: $(el),
        toolbar: [
          'title',
          'bold',
          'italic',
          'underline',
          'color',
          'ol',           //# ordered list
          'ul',           //# unordered list
          'blockquote',
          'code',         //# code block
          'table',
          'link',
          'image',
          'hr',           //# horizontal ruler
          'alignment',
          '|',
          'fullscreen'
        ],
        upload: {
          url: '/upload',
          params: null,
          fileKey: 'file',
          connectionCount: 3,
          leaveConfirm: 'Uploading is in progress, are you sure to leave this page?'
        }
        //optional options
      });
    this.editor.on("valuechanged", ()=> {
      this.setState({content: this.editor.getValue()}, ()=> {
        this.props.output(this.editor.getValue());
      });
    });
  }
  render() {
    return (
      <div className="editor-container editor-sim">
        <textarea ref={this.textareaRef.bind(this)} autoFocus/>
      </div>
    );
  }
}
